package soar.test.jpa.check;

import soar.test.jpa.share.Resource;

public class App
{
    public static void main(String args[])
    {
        String db_type;
        if (args.length < 1)
        {
            System.err.println("args empty");
            System.exit(1);
        }
        db_type = args[0].toUpperCase();
        new App().run(db_type);
        System.exit(0);
    }

    private void run(String db_type)
    {
        try
        {
            String persistence_unit = db_type.toLowerCase();

            init_database(persistence_unit, db_type);

            test_entity(persistence_unit, db_type);

            close_database(persistence_unit);
        }
        catch (Exception e)
        {
            System.err.println(String.format("connect fail: %s", e));
            return;
        }
    }

    private void init_database(String persistence_unit, String db_type)
            throws Exception
    {
        Conf conf = new Conf();
        switch (db_type)
        {
        case "MYSQL":
            conf.setUser("dbuser");
            conf.setPassword("dbuser");
            conf.setHost("localhost");
            conf.setPort(3306);
            conf.setDatabase("data");
            break;

        case "POSTGRESQL":
            conf.setUser("dbuser");
            break;

        case "ORACLE":
            conf.setUser("dbuser");
            break;

        case "SQLSERVER":
            conf.setUser("dbuser");
            break;

        default:
            throw new Exception(String.format("db_type(%s) invalid", db_type));
        }
        Resource.setPersistenceProperties(persistence_unit, db_type,
                conf.getUser(), conf.getPassword(), conf.getHost(),
                conf.getPort(), conf.getDatabase());
    }

    private void close_database(String persistence_unit) throws Exception
    {
        Resource.getInstance().getEntityManagerHandler(persistence_unit)
                .close();
    }

    private void test_entity(String persistence_unit, String db_type)
            throws Exception
    {
        for (int i = 0; i < 2; i++)
        {
            switch (db_type)
            {
            case "MYSQL":
                MySQL.testEntity(persistence_unit);
                break;

            case "POSTGRESQL":
                break;

            case "ORACLE":
                break;

            case "SQLSERVER":
                break;

            default:
                throw new Exception(
                        String.format("db_type(%s) invalid", db_type));
            }
            Thread.sleep(1*1000);
        }
    }
}
